<?php
class Master extends CI_Controller {

	function master()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->load->library('encrypt');
		$this->load->model('mmaster');
		$this->load->model('mglobal');
		$this->load->model('magents');
        $this->load->model('moutlets');
        $this->load->helper('url');
		#$this->is_logged_in();
		#$this->mjadwal->saveLog();
	}

	function is_logged_in()
	{
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			redirect(base_url() .'index.php/login');
		}
	}

	function usermanagement($proses="",$id="")
	{
		$data['template'] = "shell/smooth";
                $data['users']    = $this->mmaster->getUser();
                $data['main_view']      = 'f-users';
		$data['proses']		= $proses;
		$data['id']	= $id;

		$data['data'] = array("name"=>"","email"=>"","username"=>"","password"=>"");
		if($proses<>"" && $id<>""){
		    $getdata = $this->mmaster->getUser($id);
		    foreach($getdata as $r){
			$data['data']['name'] 		= $r->name;
			$data['data']['email'] 		= $r->email;
			$data['data']['username'] 	= $r->username;
			$data['data']['password'] 	= $r->password;
		    }
		}
		#inisialisasi elemen form yang harus diisi
		$this->form_validation->set_rules('name', 'Nama', 'required');
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_vemail_check');

		$this->form_validation->set_error_delimiters('<li>','</li>');
		$this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');
		$this->form_validation->set_message('valid_email', 'Kolom <b>%s</b> harus diisi dengan alamat email yang benar.');

		if ($this->form_validation->run() != FALSE){
			// masukkan data di sini
			$this->mmaster->saveUser($id);
			$this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
			redirect(base_url()."index.php/master/usermanagement");
		}

                $hasil = "";
                $this->load->view($data['template'],$data);
	}


        function distributor($proses="",$id="")
	{
		$data['template'] = "shell/smooth";
                $data['users']    = $this->mmaster->getDistributor();
                $data['main_view']      = 'f-distributor';
		$data['proses']		= $proses;
		$data['id']	= $id;

		$data['data'] = array("name"=>"","distributor_add"=>"","distributor_id"=>"");
		if($proses<>"" && $id<>""){
		    $getdata = $this->mmaster->getDistributor($id);
		    foreach($getdata as $r){
			$data['data']['name'] 		        = $r->distributor_name;
			$data['data']['distributor_add'] 	= $r->distributor_add;
			$data['data']['distributor_id'] 	= $r->distributor_id;
		    }
		}

		#inisialisasi elemen form yang harus diisi
		$this->form_validation->set_rules('name', 'Nama', 'required');
		$this->form_validation->set_rules('distributor_add', 'Dstributor Add', 'required');

		$this->form_validation->set_error_delimiters('<li>','</li>');
		$this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');

		if ($this->form_validation->run() != FALSE){
			// masukkan data di sini
			$this->mmaster->saveDistributor($id);
			$this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
			redirect(base_url()."index.php/master/distributor");
		}

                $hasil = "";
                $this->load->view($data['template'],$data);
	}

	function agents( $param1="", $param2="", $param3="" )
	{
		// if($param1 == 'new')
		// {
		// 	// echo 'test';die();
		// }

		//decode id
		$param2 = $this->enc->defog($param2); 

		$data = $this->initializeArray( 'agent' );
		$arr = array( 'a_status', 'identity', 'o_location', 'a_type', 'b_focus' );
		
		if ($param1!="")
    {

    	$fillData = $this->fillData( $arr, 'direct sales' );
      $data = array_merge( $data, $fillData );

    }
		
		$data[ 'agent_id' ] ="";// $this->magents->generateAgentID();
		$result = '';
		$pic = '';
	//	$data['user_group_id']=$this->mmaster->getUserRole();
        //print_r ($data['user_group_id'][0]['user_group_id']);
      
        
		if( $param1 == "update" || $param1 == "approve" )
		{
			$result = $this->magents->getAgents( "", $param2 );
       // $result2 = $this->magents->getUnapprovedAgents( $param2 );
		} //else
        //{
            
        //}
        
		
		if( $param1 == "bank" )
		{
			$bankData = $this->bank( $param2, $param3, 'agent' );
			$data = array_merge( $data, $bankData );
		}
		else if( $param1 == "update" )
		{
			$pic = $this->magents->getPIC( $param2 );
			$pic2 = $this->magents->getUnapprovedPIC( $param2 );

			// Ambil program agent dan program yang sedang aktif/berjalan
			// Program yg aktif untuk menambahkan tanda centang
			// yaddis@nutech 09/19/2012
			$agent_program = $this->mmaster->getPrograms($param2);
			$data['agent_programs'] = $this->mmaster->getActivePrograms($param2);

			// print_r($agent_program); die();
			if( $result != null )
			{
				$data[ 'agent_name' ] = $result->agent_name;
				$data[ 'agent_status' ] = $result->agent_status;
				$data[ 'agent_address' ] = $result->agent_address;
				$data[ 'agent_city' ] = $result->agent_city;
				$data[ 'agent_province' ] = $result->agent_province_id;
				$data[ 'agent_id' ] = $result->agent_id;
				$data[ 'agent_zip_code' ] = $result->agent_zip_code;
				$data[ 'agent_phone_no' ] = $result->agent_phone_no;
				$data[ 'agent_mdn_evo' ] = $result->agent_mdn_evo; 
				$data[ 'maintain_nam' ] = $this->mmaster->getMaintainName( $result->territory_id , 'direct sales');
                $data[ 'agent_website' ] = $result->agent_website; 
				$data[ 'is_school' ] = $result->is_agent_a_school; 
				$data[ 'image' ] = $result->image_path;
				$data['agent_selling_type']=$result->agent_selling_type;

        if($agent_program) {
            $data['program'] = $agent_program;
        }

				if( $data[ 'is_school' ] == true )
				{
					
					$school = $this->magents->getAgentSchool( $param2 );
					$data[ 'majority_num' ] = $school->school_number_of_majority;
					$data[ 'faculty_num' ] = $school->school_number_of_faculty;
					$data[ 'student_num' ] = $school->school_number_of_student;
					$data[ 'teacher_num' ] = $school->school_number_of_teacher;
				}
				
				$data[ 'employee_num' ] = $result->agent_number_of_employee; 
				$data[ 'agent_location' ] = $result->agent_location; 
				$data[ 'agent_type' ] = $result->agent_type; 
				$data[ 'agent_business_focus' ] = $result->agent_business_focus; 
			}
			
			if( $pic != null )
			{
				$data[ 'pic_name' ] = $pic->pic_name;
				$data[ 'pic_phone' ] = $pic->pic_phone_no;
				$data[ 'pic_address' ] = $pic->pic_address;
				$data[ 'pic_city' ] = $pic->pic_city;
				$data[ 'pic_province' ] = $pic->pic_province_id;
				$data[ 'pic_zip_code' ] = $pic->pic_zip_code;
				$data[ 'pic_identity_type' ] = $pic->pic_identity_type;
				$data[ 'pic_identity_no' ] = $pic->pic_identity_no;
				$data[ 'pic_birth_place' ] = $pic->pic_birth_place;
				$data[ 'pic_birth_date' ] = $pic->pic_birth_date;
				$data[ 'pic_job_position' ] = $pic->pic_job_position;
				$data[ 'pic_smartfren_no' ] = $pic->pic_smartfren_no;
				$data[ 'pic_mobile_no' ] = $pic->pic_mobile_no;
				$data[ 'pic_email' ] = $pic->pic_email;
                
/**
 *                 
 *                 $data['old'][ 'pic_name' ] = $pic->pic_name;
 * 				$data['old'][ 'pic_phone' ] = $pic->pic_phone_no;
 * 				$data['old'][ 'pic_address' ] = $pic->pic_address;
 * 				$data['old'][ 'pic_city' ] = $pic->pic_city;
 * 				$data['old'][ 'pic_province' ] = $pic->pic_province_id;
 * 				$data['old'][ 'pic_zip_code' ] = $pic->pic_zip_code;
 * 				$data['old'][ 'pic_identity_type' ] = $pic->pic_identity_type;
 * 				$data['old'][ 'pic_identity_no' ] = $pic->pic_identity_no;
 * 				$data['old'][ 'pic_birth_place' ] = $pic->pic_birth_place;
 * 				$data['old'][ 'pic_birth_date' ] = $pic->pic_birth_date;
 * 				$data['old'][ 'pic_job_position' ] = $pic->pic_job_position;
 * 				$data['old'][ 'pic_smartfren_no' ] = $pic->pic_smartfren_no;
 * 				$data['old'][ 'pic_mobile_no' ] = $pic->pic_mobile_no;
 * 				$data['old'][ 'pic_email' ] = $pic->pic_email;*/
			} else {
			 $data[ 'pic_name' ] = "";
				$data[ 'pic_phone' ] = "";
				$data[ 'pic_address' ] = "";
				$data[ 'pic_city' ] = "";
				$data[ 'pic_province' ] = "";
				$data[ 'pic_zip_code' ] ="";
				$data[ 'pic_identity_type' ] = "";
				$data[ 'pic_identity_no' ] ="";
				$data[ 'pic_birth_place' ] = "";
				$data[ 'pic_birth_date' ] = "";
				$data[ 'pic_job_position' ] = "";
				$data[ 'pic_smartfren_no' ] = "";
				$data[ 'pic_mobile_no' ] = "";
				$data[ 'pic_email' ] = "";
             
			}
		}
        $registered[]=' ';
        $edit[]=' ';
        $new[]=' ';
        $user_role=$this->mmaster->checkUserRole(56);
        if($user_role['menu_add']){
            
        }
        if($user_role['menu_view']){
            $registered[]='<a class="viewBtnNew" href="'.base_url().'index.php/act_agents/view/">View</a>';
    		$edit[]='<a class="viewBtnNew" href="'.base_url().'index.php/act_agents/viewDiff/">View</a>';
            $new[]='<a class="viewBtnNew" href="'.base_url().'index.php/act_agents/view/">View</a>';   
        }
        if($user_role['menu_edit']){
            $registered[]='<a class="updateBtnNew" href="'.base_url().'index.php/master/agents/update/">Edit</a>';
    		$edit[]='<a class="updateBtnNew" href="'.base_url().'index.php/master/agents/update/">Edit</a>';
            $new[]='<a class="updateBtnNew" href="'.base_url().'index.php/master/agents/update/">Edit</a>'; 
        }
        if($user_role['menu_delete']){
            $registered[]='<a class="deleteBtn" href="'.base_url().'index.php/act_agents/delete/primer/">Delete</a>';
    	}
        if($user_role['menu_approve']){
            $edit[]='<a class="approveBtnNew" href="'.base_url().'index.php/master/agents/approve/">Approve</a>';
            $new[]='<a class="approveBtnNew" href="'.base_url().'index.php/master/agents/approve/">Approve</a>'; 
        }
        if($user_role['menu_reject']){
            $edit[]='<a class="rejectBtnNew" href="'.base_url().'index.php/act_agents/delete/temp/">Reject</a>';
            $new[]='<a class="rejectBtnNew" href="'.base_url().'index.php/act_agents/delete/primer/">Reject</a>'; 
        }
        // inisialisasi dan validasi form
        $data['menu']['registered']=implode(" | ",$registered);
        $data['menu']['edit']=implode(" | ",$edit);
        $data['menu']['new']=implode(" | ",$new);
        if($data['menu']['registered']==null){
            $data['menu']['registered']='';
        }
        if($data['menu']['edit']==null){
            $data['menu']['edit']='';
        }
        if($data['menu']['new']==null){
            $data['menu']['new']='';
        }
		$this->form_validation->set_rules('agent_selling_type', 'Tipe Penjualan', 'required');
		$this->form_validation->set_rules('agent_name', 'Nama Agen/Lokasi', 'required');
		$this->form_validation->set_rules('agent_address', 'Alamat Agen/Lokasi', 'required');
		$this->form_validation->set_rules('agent_city', 'Kota', 'required');
		$this->form_validation->set_rules('agent_type', 'Tipe Agen', 'required');
		//$this->form_validation->set_rules('pic_name', 'Nama PIC', 'required');
		           
		if( $param1 == 'approve' )
		{
			$this->magents->updateAgents( $param1, $result->agent_id, $result->territory_id, $result->is_agent_a_school );
			$this->session->set_flashdata('message', 'Data sudah disetujui');

			//update by: alfin akhret
            $this->magents->update_message($this->session->userdata('username') ,'Pesan dari System', $result->agent_id, 'Agent disetujui'); 

			redirect(base_url()."index.php/master/agents");
		}
		
		if ($this->form_validation->run() != FALSE)
		{
			$message = '';
			if( $param1 == 'update' )
			{
			 $a=	$this->magents->updateAgents( $param1, $result->agent_id, $result->territory_id, $result->is_agent_a_school );
				$message = $a;//'Data berhasil diubah'.$a.'kk';
			}
			else
			{
				//$data[ 'agent_id' ] = $this->magents->generateAgentID();
				/****************************************************************
				/****************************** PENTINGGGG!!!! ******************/
				
				$this->magents->saveAgents();
				$message = "Data No ".$data['agent_id']." berhasil dimasukkan";
			}
			$this->session->set_flashdata('message', $message);
			redirect(base_url()."index.php/master/agents");
		}			
		
		$this->load->view($data['template'],$data);


	}
	
	
	/* function initializeArray
	 * @author: Willy Halim Dinata
	 * @param:
	 *		$name => nama entitas
	 */
	private function initializeArray( $name )
	{
		if( $name == 'agent' )
		{
			$data['template'] = "shell/smooth";
			$data['main_view'] = 'f-agents';
			$data[ 'agent_name' ] = null;
			$data[ 'agent_address' ] = null;
			$data[ 'agent_city' ] = null;
			$data[ 'agent_province' ] = null;
			$data[ 'agent_id' ] = null;
			$data[ 'agent_zip_code' ] = null;
			$data[ 'agent_phone_no' ] = null;
			$data[ 'agent_mdn_evo' ] = null;
			$data[ 'image' ] = null;
			$data[ 'maintain_name' ] = null; 
			$data[ 'is_school' ] = null; 	
			$data[ 'majority_num' ] = null;
			$data[ 'faculty_num' ] = null;
			$data[ 'student_num' ] = null;
			$data[ 'teacher_num' ] = null;		
			$data[ 'employee_num' ] = null; 
			$data[ 'agent_location' ] = null; 
			$data[ 'agent_type' ] = null; 
			$data[ 'agent_selling_type' ] = null;  // yaddi
			$data[ 'agent_business_focus' ] = null; 
			$data[ 'agent_website' ] = null; 
			$data[ 'pic_name' ] = null;
			$data[ 'pic_phone' ] = null;
			$data[ 'pic_address' ] = null;
			$data[ 'pic_city' ] = null;
			$data[ 'pic_province' ] = null;
			$data[ 'pic_zip_code' ] = null;
			$data[ 'pic_identity_type' ] = null;
			$data[ 'pic_identity_no' ] = null;
			$data[ 'pic_birth_place' ] = null;
			$data[ 'pic_birth_date' ] = null;
			$data[ 'pic_job_position' ] = null;
			$data[ 'pic_smartfren_no' ] = null;
			$data[ 'pic_mobile_no' ] = null;
			$data[ 'pic_email' ] = null;
		}
		else if( $name == "outlet" )
		{
			$data['template'] = "shell/smooth";
			$data['main_view'] = "f-outlets";
			$data[ 'maintain_name' ] = null; 
			$data[ 'building' ] = null; 
			$data[ 'branding_status' ] = '';
			$data[ 'full_branding' ] = '';
			$data[ 'contract_end' ] = '';
			$data[ 'value' ] = '';
			$data[ 'owner_name' ] = '';
			$data[ 'owner_gender' ] = '';
			$data[ 'owner_birth_place' ] = '';
			$data[ 'owner_birth_date' ] = '';
			$data[ 'owner_religion' ] = '';
			$data[ 'owner_email' ] = '';
			$data[ 'owner_phone' ] = '';
			$data[ 'owner_identity_type' ] = '';
			$data[ 'owner_identity_number' ] = '';
			$data[ 'outbond' ] = '';
			$data[ 'outlet_id' ] = '';
			$data[ 'outlet_status' ] = '';
			$data[ 'outlet_type' ] = '';
			$data[ 'outlet_size' ] = '';
			$data[ 'outlet_location' ] = '';
			$data[ 'outlet_employee_number' ] = '';
			$data[ 'outlet_lifetime' ] = '';
			$data[ 'outlet_ownership' ] = '';
			$data[ 'outlet_smart_no' ] = '';
			$data[ 'outlet_business_focus' ] = '';
			$data[ 'outlet_customer_type' ] = '';
			$data[ 'outlet_size_of_business' ] = '';
			$data[ 'outlet_expansion_package' ] = '';
			$data[ 'outlet_join_lajang' ] = '';
			$data[ 'outlet_lajang_package' ] = '';
			$data[ 'outlet_lajang_is_reorder' ] = '';
			$data[ 'outlet_address' ] = '';
			$data[ 'outlet_name' ] = '';
			$data[ 'outlet_city' ] = '';
			$data[ 'outlet_province' ] = '';
			$data[ 'outlet_post_code' ] = '';
			$data[ 'outlet_phone' ] = '';
			$data[ 'outlet_eload_number' ] = '';
			$data[ 'outlet_business_structure' ] = '';
		}
		else if( $name == "bank" )
		{
			$data[ 'bank_name' ] = '';
			$data[ 'bank_branch' ] = '';
			$data[ 'bank_account_name' ] = '';
			$data[ 'bank_account_number' ] = '';
		}
		else
		{
			$data[ 'front_type' ] = '';
			$data[ 'front_name' ] = '';
			$data[ 'front_birth_place' ] = '';
			$data[ 'front_birth_date' ] = '';
			$data[ 'front_identity_type' ] = '';
			$data[ 'front_identity_no' ] = '';
			$data[ 'front_religion' ] = '';
			$data[ 'front_work' ] = '';
			$data[ 'front_marital' ] = '';
			$data[ 'front_address' ] = '';
			$data[ 'front_city' ] = '';
			$data[ 'front_province' ] = '';
			$data[ 'front_zip' ] = '';
			$data[ 'front_mdn' ] = '';
			$data[ 'front_remark' ] = '';
		}
		
		return $data;
	}
	
	private function fillData( $arr, $type )
	{		
		foreach( $arr as $combo )
		{
			$query = $this->mmaster->getComboData( $combo );
			$i = 0;
			foreach( $query->result() as $r )
			{
				$data[ 'data' ][ $combo ][ 'member_value' ][ $i ] = $r->member_value;
				$data[ 'data' ][ $combo ][ 'member_display' ][ $i ] = $r->member_display;
				$i++;
			}
		}
		
		/**************************** ISI COMBO PROVINCE *****************************/
		$query = $this->mmaster->getRecord( 't_mtr_province' );
		$i = 0;
		foreach( $query->result() as $r )
		{
			$data[ 'data' ][ 'province' ][ 'member_value' ][ $i ] = $r->province_id;
			$data[ 'data' ][ 'province' ][ 'member_display' ][ $i ] = $r->province_name;
			$i++;
		}
				
		/*******************************ISI TERRITORY PATH******************************/
		$result = $this->mmaster->getTerritoryPath( $this->session->userdata( 'username' ), 'cluster' );
		$data[ 'data' ][ 'tr_path' ][ 'member_display' ] = $result[ 'path' ];
		$data[ 'data' ][ 'tr_path' ][ 'member_value' ] = $result[ 'territory_id' ];
		
		
		/************* ISI COMBO FIELD NAME PADA MAINTAINED BY *************************/
		$query = $this->mmaster->getMaintainName( '', $type );
		$i = 0;
      //  print_r($query);return;
		if( $query != null )
		{
			foreach( $query->result() as $r )
			{
				$data[ 'data' ][ 'maintain_name' ][ 'member_display' ][ $i ] = $r->user_name;
				$data[ 'data' ][ 'maintain_name' ][ 'member_value' ][ $i ] = $r->user_id;
				$data[ 'data' ][ 'maintain_name' ][ 'pos' ][ $i ] = $this->mmaster->getPosition( $r->user_id )->row()->user_group_name;
				$i++;
			}
		}
		else
		{
			$data[ 'data' ][ 'maintain_name' ][ 'member_display' ][ $i ] = '';
			$data[ 'data' ][ 'maintain_name' ][ 'member_value' ][ $i ] = '';
			$data[ 'data' ][ 'maintain_name' ][ 'pos' ][ $i ] = '';				
		}
		return $data;
	}
	
	
	/* function outlets
	 * @author: Willy Halim Dinata
	 * @param:
	 *		$param1 => proses dari outlet (new/update) atau bank atau frontliner
	 *		$param2 => id dari outlet atau proses dari bank/frontliner (new/update)
	 *		$param3 => id dari bank/frontliner
	 */
	function outlets( $param1="", $param2="", $param3=""  )
	{
		$data = $this->initializeArray( 'outlet' );
		/****************************** ISI COMBO**********************************/
		$arr = array( 'building', 'gender', 'religion', 'identity', 'o_status', 'o_type', 'o_size', 
						'o_location', 'o_ownership', 'b_structure', 'b_focus', 'b_size', 'c_type', 
						'l_package', 'e_package', 'position', 'full_branding', 'outbond', 'front_type', 
						'marital' );
		
		$fillData = $this->fillData( $arr, 'smart fren ambassador' );
		$data = array_merge( $data, $fillData );
		
		if( $param1 == 'frontliners' )
		{	
			$frontlinerData = $this->frontliner( $param2, $param3 );
			$data = array_merge( $data, $frontlinerData );
		}
		else if( $param1 == 'bank' )
		{
			$bankData = $this->bank( $param2, $param3, 'outlet' );
			$data = array_merge( $data, $bankData );
		}
		else
		{
			if( $param1 == 'update' )
			{
				$updateData = $this->updateOutlet( $param2 );
				$data = array_merge( $data, $updateData );
			}
			
			/******************************** VALIDATION *************************/
			//$this->form_validation->set_rules( 'name_owner', 'Owner Name', 'required|max_length[30]' );
			$this->form_validation->set_rules( 'outlet_name', 'Outlet Name', 'required|max_length[255]' );
			$this->form_validation->set_rules( 'address', 'Outlet Address', 'required|max_length[255]' );
			$this->form_validation->set_rules( 'city', 'Outlet City', 'required|max_length[100]' );
			//$this->form_validation->set_rules( 'province', 'Province', 'required|max_length[100]' );
			//$this->form_validation->set_rules( 'post_code', 'Post Code', 'numeric|max_length[10]' );
			//$this->form_validation->set_rules( 'employee_num', 'Employee Number', 'required|numeric|max_length[10]' );
			//$this->form_validation->set_rules( 'outlet_lifetime', 'Outlet Lifetime', 'required|numeric|max_length[10]' );
			//$this->form_validation->set_rules( 'birth_place', 'Birth Place', 'max_length[50]' );
			//$this->form_validation->set_rules( 'birth_date', 'Birth Date', 'required' );
			//$this->form_validation->set_rules( 'email', 'Email', 'valid_email|max_length[50]' );
			//$this->form_validation->set_rules( 'phone', 'Phone', 'integer|max_length[20]' );
			//$this->form_validation->set_rules( 'identity_number', 'Identity Number', 'integer|max_length[50]' );
			//$this->form_validation->set_rules( 'branding_value', 'Branding Value', 'required|numeric' );
			////$this->form_validation->set_rules( 'identity_number', 'Identity Number', 'integer|max_length[50]' );
			
			
			if( $param1 == 'approve' )
			{
				$this->moutlets->updateOutlet( $param2 );
				$this->session->set_flashdata('message', 'Outlet sudah disetujui');
				
				redirect(base_url()."index.php/master/outlets");
			}
			
			if( $this->form_validation->run() != FALSE )
			{
				if( $param1 == 'update' )
				{
					$this->moutlets->saveOutlets( $param2, $param1 );
					$this->session->set_flashdata('message', 'Data Outlet Berhasil diubah');
				}
				else
				{
					$this->moutlets->saveOutlets( '', $param1 );
					$this->session->set_flashdata('message', 'Data Outlet Berhasil dimasukkan');
				}
				
				redirect(base_url()."index.php/master/outlets");
			}	
		}
		
		$this->load->view($data['template'],$data);
	}
	
	
	private function updateOutlet( $id )
	{
		$outlet = $this->db->get_where( 't_mtr_outlet', array( 'outlet_id' => $id ) )->row(); 
		$outlet_data = $this->db->get_where( 't_mtr_outlet_data', array( 'outlet_id' => $id ) )->row();
		$outlet_branding = $this->db->get_where( 't_mtr_outlet_branding', array( 'outlet_id' => $id ) )->row();				
		$outlet_owner = $this->db->get_where( 't_mtr_outlet_owner', array( 'outlet_id' => $id ) )->row();
				
		if( $outlet_data != null && $outlet != null )
		{
			$data[ 'building' ] = $outlet_data->outlet_building;
			$data[ 'maintain_name' ] = $this->mmaster->getMaintainName( $outlet->territory_id );
			
			if( $outlet_branding != null )
			{
				$data[ 'branding_status' ] = $outlet_branding->branding_status;
				$data[ 'full_branding' ] = $outlet_branding->full_branding_by;
				$data[ 'contract_end' ] = $outlet_branding->contract_end;
				$data[ 'value' ] = $outlet_branding->branding_value;
			}
			
			if( $outlet_owner != null )
			{
				$data[ 'owner_name' ] = $outlet_owner->owner_name;
				$data[ 'owner_gender' ] = $outlet_owner->owner_gender;
				$data[ 'owner_birth_place' ] = $outlet_owner->owner_birth_place;
				//$data[ 'owner_birth_date' ] = $outlet_owner->owner_birth_date;
				$data[ 'owner_religion' ] = $outlet_owner->owner_religion;
				$data[ 'owner_email' ] = $outlet_owner->owner_email;
				$data[ 'owner_phone' ] = $outlet_owner->owner_phone;
				$data[ 'owner_identity_type' ] = $outlet_owner->owner_identity_type;
				$data[ 'owner_identity_number' ] = $outlet_owner->owner_identity_number;
			}
			
			$data[ 'outbond' ] = $outlet->outbond_caller_id;
			$data[ 'outlet_id' ] = $outlet->outlet_id;
			$data[ 'outlet_status' ] = $outlet_data->outlet_status;
			$data[ 'outlet_type' ] = $outlet_data->outlet_type;
			$data[ 'outlet_size' ] = $outlet_data->outlet_size;
			$data[ 'outlet_location' ] = $outlet_data->outlet_location;
			$data[ 'outlet_employee_number' ] = $outlet_data->outlet_employee_number;
			$data[ 'outlet_lifetime' ] = $outlet_data->outlet_lifetime;
			$data[ 'outlet_ownership' ] = $outlet_data->outlet_ownership;
			$data[ 'outlet_smart_no' ] = $outlet_data->outlet_smart_no;
			$data[ 'outlet_business_focus' ] = $outlet_data->outlet_business_focus;
			$data[ 'outlet_customer_type' ] = $outlet_data->outlet_customer_type;
			$data[ 'outlet_size_of_business' ] = $outlet_data->outlet_size_of_business;
			$data[ 'outlet_expansion_package' ] = $outlet_data->outlet_expansion_package;
			$data[ 'outlet_join_lajang' ] = $outlet_data->outlet_join_lajang;
			$data[ 'outlet_lajang_package' ] = $outlet_data->outlet_lajang_package;
			$data[ 'outlet_lajang_is_reorder' ] = $outlet_data->outlet_lajang_is_reorder;
			$data[ 'outlet_address' ] = $outlet->address;
			$data[ 'outlet_name' ] = $outlet->outlet_name;
			$data[ 'outlet_city' ] = $outlet->city;
			$data[ 'outlet_province' ] = $outlet->province_id;
			$data[ 'outlet_post_code' ] = $outlet->post_code;
			$data[ 'outlet_phone' ] = $outlet->phone;
			$data[ 'outlet_eload_number' ] = $outlet->eload_number;
			$data[ 'outlet_business_structure' ] = $outlet->business_structure;
		}
		
		return $data;
	}
	
	
	private function bank( $proses, $id, $type )
	{			
		$data = $this->initializeArray( 'bank' );
		if( $proses == 'update' )
		{
			$bank = $this->mmaster->getBanks( $id );
			
			$data[ 'bank_name' ] = $bank->bank_name;
			$data[ 'bank_branch' ] = $bank->bank_branch;
			$data[ 'bank_account_name' ] = $bank->bank_account_name;
			$data[ 'bank_account_number' ] = $bank->bank_account_number;
			$tr_id = $this->db->get_where( 't_mtr_bank_account', array( 'bank_account_id' => $id ) )->row()->territory_id;
			$query = $this->db->get_where( 't_mtr_'.$type, array( 'territory_id' => $tr_id ) )->row();
		}
			
		$this->form_validation->set_rules( 'bank_name', 'Bank Name', 'required|max_length[30]' );
		
		if( $this->form_validation->run() != FALSE )
		{
			$this->mmaster->saveBank( $id, $proses, $type );
			
			if( $proses == "new" )
				$this->session->set_flashdata('message', 'Data Bank Berhasil dimasukkan');
			else
				$this->session->set_flashdata('message', 'Data Bank Berhasil diubah');
				
			if( $proses == "update" )
			{
				if( $type == "outlet" )
					$id = $query->outlet_id;
				else
					$id = $query->agent_id;
			}
			
			
			if( $type == 'outlet' )
				redirect(base_url()."index.php/master/outlets");
			else
				redirect(base_url()."index.php/master/agents");
		}
		
		return $data;
	}
	
	private function frontliner( $proses, $id )
	{
		$data = $this->initializeArray( 'frontliner' );
		if( $proses == "update" )
		{
			$front = $this->moutlets->getFrontliners( $id );
			
			$data[ 'front_type' ] = $front->frontliner_type;
			$data[ 'front_name' ] = $front->frontliner_name;
			$data[ 'front_birth_place' ] = $front->frontliner_birth_place;
			$data[ 'front_birth_date' ] = $front->frontliner_birth_date;
			$data[ 'front_identity_type' ] = $front->frontliner_identity_type;
			$data[ 'front_identity_no' ] = $front->frontliner_identity_no;
			$data[ 'front_religion' ] = $front->frontliner_religion;
			$data[ 'front_work' ] = $front->frontliner_work_experience;
			$data[ 'front_marital' ] = $front->frontliner_marital_status;
			$data[ 'front_address' ] = $front->frontliner_address;
			$data[ 'front_city' ] = $front->frontliner_city;
			$data[ 'front_province' ] = $front->frontliner_province_id;
			$data[ 'front_zip' ] = $front->frontliner_zip_code;
			$data[ 'front_mdn' ] = $front->frontliner_mdn_smartfren;
			$data[ 'front_remark' ] = $front->frontliner_remark;
		}
		
		$this->form_validation->set_rules( 'front_name', 'Frontliner Name', 'required|max_length[30]' );
		
		if( $this->form_validation->run() != FALSE )
		{
			$this->moutlets->saveFrontliners( $this->enc->defog($id), $proses );
			
			if( $proses == "new" )
				$this->session->set_flashdata('message', 'Data Frontliner Berhasil dimasukkan');
			else
				$this->session->set_flashdata('message', 'Data Frontliner Berhasil diubah');
			
			redirect(base_url()."index.php/outlet/outlets/update/".$id);
		}
		
		return $data;
	}

	function salesOrder($act="",$page="")
	{
		$data['template'] = "shell/smooth";
        $data['main_view']     = 'f-sales';
        $this->load->view($data['template'],$data);
	}

    function gallery($proses = "", $id = "")
	{
		$data['template'] = "shell/smooth";
        $data['main_view']     = 'f-gallery';
        $data['proses'] = $proses;
        $data['id'] = $id;
        $data['cluster'] = $this->mmaster->getCluster();

        $data['data'] = array("gallery_name" => "", "gallery_address" => "", "gallerys_cluster" =>
            "");
        if ($proses <> "" && $id <> "") {
            $getdata = $this->mmaster->getGallery($id);
            $data['getdetail'] = $this->mmaster->getGalleryDetail($id);
            foreach ($getdata as $r) {
                $data['data']['gallery_name'] = $r->gallery_name;
                $data['data']['gallery_address'] = $r->gallery_address;
            }
        }

        #inisialisasi elemen form yang harus diisi
        $this->form_validation->set_rules('gallery_name', 'Gallery Name', 'required');
        $this->form_validation->set_rules('gallery_address', 'Dstributor Add','required');
        $this->form_validation->set_rules('territory_id[]', 'Gallery Cluster','required|numeric');


        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');

        if ($this->form_validation->run() != false){

            // masukkan data di sini
            $config['upload_path'] = './file/Gallery';
            $config['allowed_types'] = 'gif|jpg|png|pdf|jpeg|doc';
            $config['max_size']	= '10000';
            $config['max_width']  = '2000';
            $config['max_height']  = '2000';
            $fileinfo = array();
            $result_array = array();

            $this->load->library('upload', $config);

            if(!empty($_FILES['image_path']['name']))
				{
				    if(!$this->upload->do_upload())
					{
                        //$error = array('error' => $this->upload->display_errors());
                        //print_r($error);
                        $this->upload->display_errors('<p>', '</p>');                        
                    }
                    else
                    {
			             array_push($result_array,$this->upload->data());
                    }
                }
            else
            {
                $this->session->set_flashdata('message', 'Kesalahan dalam mengupload');
                redirect(base_url() . "index.php/master/gallery");
            }

            $this->mmaster->saveGallery($id, $result_array);
            $galleryFresh = null;
            $gallery_id = '';
            $territory_id = $this->input->post('territory_id');

            if ($proses <> "" && $id <> "")
            {
                $this->mmaster->deleteGalleryDetail($id);
                for($i = 0; $i < sizeof($territory_id); $i++)
                {
                    $this->mmaster->saveGalleryDetail($id, $i);
                }
            }
            else
            {
                $galleryFresh = $this->mmaster->getFreshGallery();
                $gallery_id = $galleryFresh->gallery_id;


                for($i = 0; $i < sizeof($territory_id); $i++)
                {
                    $this->mmaster->saveGalleryDetail($gallery_id, $i);
                }
            }



            $this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
            redirect(base_url() . "index.php/master/gallery");
        }
         $this->load->view($data['template'],$data);
	}

	function handset($proses="",$id="")
	{
		$data['template'] = "shell/smooth";
                $data['users']    = $this->mmaster->getHandset();
                $data['main_view']      = 'f-handset';
		$data['proses']		= $proses;
		$data['id']	= $id;
		
		$data['data'] = array("model"=>"","man"=>"","sales"=>"","imei"=>"", "imsi"=>"", "msisdn"=>"", "salesId"=>"");
		if($proses<>"" && $id<>""){
		    $getdata = $this->mmaster->getHandset($id);
		    foreach($getdata as $r){
			$data['data']['model'] 	= $r->handset_model;
			$data['data']['man'] 	= $r->handset_man;
			$data['data']['sales'] 	= $r->user_name;
			$data['data']['salesId']= $r->user_id;
			$data['data']['imei'] 	= $r->imei;
			$data['data']['imsi'] 	= $r->imsi;
			$data['data']['msisdn']	= $r->msisdn;
		    }
		}
		
		#inisialisasi elemen form yang harus diisi
		$this->form_validation->set_rules('model', 'Model', 'required');
		$this->form_validation->set_rules('man', 'Man', 'required');
		$this->form_validation->set_rules('salesId', 'Sales', 'required');
		$this->form_validation->set_rules('imei', 'IMEI', 'required');
		$this->form_validation->set_rules('imsi', 'IMSI', 'required');
		$this->form_validation->set_rules('msisdn', 'MSISDN', 'required');
		
		$this->form_validation->set_error_delimiters('<li>','</li>');
		$this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');
                
		if ($this->form_validation->run() != FALSE){
			// masukkan data di sini
			$this->mmaster->saveHandset($id);
			$this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
			redirect(base_url()."index.php/master/handset");
		}	
		
                $hasil = "";
                $this->load->view($data['template'],$data);
	}
	
	function getProgram($sid, $program)
	{
		$pType = $this->checkType($sid);		
		
		$userLogin = $this->session->userdata('username');
		$dbconn  = $this->load->database("default", TRUE);
		
		if ($program == "ho")
		{
			$sql = "select program_id as mvalue, caption as mdisplay
					from t_mtr_program
					where territory_id = 1 and program_type_id = '$pType' and istatus = 1
					order by caption asc";
		}
		else
		{
			$sql = "select program_id as mvalue, caption as mdisplay
					from t_mtr_program
					where territory_id = f_get_cluster('$userLogin') and program_type_id = '$pType' and istatus = 1
					order by caption asc";
		}
        $query = $dbconn->query($sql);
		
		if( $query->num_rows() > 0 ) {
            echo json_encode($query->result());
		} 
		else {
            return array();
        }
	}
	
	function checkType( $id )
	{
		$query = $this->db->get_where( "t_mtr_outlet", array( "outlet_id" => $id ) )->row();
		if( $query == null )
			return 2;
		else 
			return 1;
	}
	
	function getChoosenProgram( $id, $program )
	{
		$userLogin = $this->session->userdata('username');
		if( $program == "ho" )
			$sql = "SELECT * from t_mtr_program prog JOIN t_mtr_channel_program chan ON chan.program_id = prog.program_id AND prog.territory_id = 1 AND chan.channel_id = '$id'";
		else
			$sql = "SELECT * from t_mtr_program prog JOIN t_mtr_channel_program chan ON chan.program_id = prog.program_id AND prog.territory_id = f_get_cluster('$userLogin') AND chan.channel_id = '$id'";
			
		$dbconn  = $this->load->database("default", TRUE);
		$query = $dbconn->query($sql);
		
		if( $query->num_rows() > 0 ) {
            echo json_encode($query->result());
		} 
		else {
            echo json_encode(array());
        }
	}
	
	function saveProgram( $id, $type )
	{
		$temp = $this->input->post( 'program' );
		$userLogin = $this->session->userdata('username');
		if( $type == "ho" )
			$sql = "SELECT * from t_mtr_program prog JOIN t_mtr_channel_program chan ON chan.program_id = prog.program_id AND prog.territory_id = 1 AND chan.channel_id = '$id'";
		else
			$sql = "SELECT * from t_mtr_program prog JOIN t_mtr_channel_program chan ON chan.program_id = prog.program_id AND prog.territory_id = f_get_cluster('$userLogin') AND chan.channel_id = '$id'";
			
		$dbconn  = $this->load->database("default", TRUE);
		$query = $dbconn->query($sql);
		
        
        print_r($id);
		foreach( $query->result() as $result )
		{
		  //print_r ($result->program_id);return;
          //$this->db->delete( 't_mtr_channel_program', array( "channel_id" => $result->program_id ) );
          $this->db->delete( 't_mtr_channel_program', "channel_id = '$id' and program_id = $result->program_id" );//edited by dn12
          //print_r ("channel_id=>$id and program_id = $result->program_id");return;
		}
		
		if( $temp != "" )
		{
			$arrProgram = explode( ",", $temp ); 
			echo $temp;
			// print_r ($arrProgram);
			
			foreach( $arrProgram as $program )
			{
				if( $program != ' ' )
					$this->db->insert( 't_mtr_channel_program', array( 'channel_id' => $id, 'program_id' => $program ) );
			}
		}
	}
        
	function userList($proses="",$id="")
	{
		$data['template']   = "shell/smooth";
		$data['users']      = $this->mmaster->getUserList();
		$data['main_view']  = 'f-user-list';
		$data['proses']		= $proses;
		$data['id']	= $id;
		
		$data['data'] = array("user_name"=>"", "position"=>"");
		if($proses<>"" && $id<>""){
		    $getdata = $this->mmaster->getUserList($id);
		    foreach($getdata as $r){
			$data['data']['user_name'] 	= $r->user_name;
			$data['data']['position'] 	= $r->position;
		    }
		}
		$hasil = "";
                $this->load->view($data['template'],$data);
	}

	public function mfino() {
		$data['template']  = "shell/smooth";
		$data['main_view'] = 'f-mfino-list';

		$this->load->view($data['template'], $data);
	}

	public function getMfino()
	{
		$this->load->model('mupload');
		$result = $this->mupload->mFinoList();
		echo json_encode($result);
	}
        //public function readuser() {
		//echo json_encode( $this->mmaster->getUser() );

	/*
	function vemail_check($str)
	{
		$where = array("email"=>$str);
		if($this->uri->segment(4) <> "") $where = array("email"=>$str,"username !="=>$this->uri->segment(4));
		$v = $this->mglobal->showdata('username','t_users',$where,'dblokal');
		if ($v <> "")
		{
			$this->form_validation->set_message('vemail_check', 'Email <b>'. $str .'</b> sudah memiliki akun.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}*/

	function addProgram($channel_type) { //channel_type bisa jadi outlet atau agent
		
		// $data['caption'] = trim($this->input->post("caption"));
		// $data['description'] = trim($this->input->post("description"));
		$data['caption'] = trim( preg_replace( '/\s+/', ' ', $this->input->post("caption") ) );  
		$data['description'] = trim( preg_replace( '/\s+/', ' ', $this->input->post("description") ) );  
		$simpan = $this->moutlet->addNewProgram($channel_type, $data);
		echo $simpan;
	}

	// update last activity 
	function update_last_activity()
	{
		$this->mmaster->update_last_activity($this->input->post('user_id'));
	}
}